package test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import org.junit.Test;

public class Block {
	@Test
	public void client() throws Exception{
		//创建通道
		FileChannel open = FileChannel.open(Paths.get("C://Users/KX-8500/Desktop/test/logo.png"), StandardOpenOption.READ);
		//分配缓冲区
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		//创建socket通道
		SocketChannel open2 = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9988));
		//读取本地文件，并发送到服务端
		while(open.read(buffer)!=-1){
			buffer.flip();
			open2.write(buffer);
			buffer.clear();
		}
		open2.shutdownOutput();
		//获取服务端反馈
		int len=0;
		while((len=open2.read(buffer))!=-1){
			buffer.flip();
			System.out.println(new String (buffer.array(),0,len));
			buffer.clear();
		}
		open.close();
		open2.close();
	};
	
	@Test
	public void server() throws IOException{
		// 获取通道
		FileChannel open = FileChannel.open(Paths.get("C://Users/KX-8500/Desktop/test/11.png"), StandardOpenOption.WRITE,
				StandardOpenOption.CREATE);
		ServerSocketChannel open2 = ServerSocketChannel.open();
		//分配指定大小的缓冲区
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		//绑定连接
		open2.bind(new InetSocketAddress(9988));
		//获取客户端连接的通道
		SocketChannel accept = open2.accept();
		//接收客户端的数据，并保存到本地
		while(accept.read(byteBuffer)!=-1){
			byteBuffer.flip();
			open.write(byteBuffer);
			byteBuffer.clear();
		}
		
 
		//发送反馈给客户端
		byteBuffer.put("图片收到了".getBytes());
		byteBuffer.flip();
		accept.write(byteBuffer);
		accept.close();
		open.close();
		open2.close();
	}
}
